import $storage from '@/utils/storage.js'
import $config from '@/utils/config.js'

const headers = {
	'Content-Type': 'application/json;charset=UTF-8',
	'x-header-client': $config.CLIENT_ID
}


//封装post,get方法,其他的自行往下加，比如put,delete
const http = {
  get(url = '', params = {}) {
	url = $config.BASE_URL + url
	headers['authentication'] = $storage.getTokenStorage()
    return new Promise((resolve, reject) => {
      uni.request({
        url,
        params,
        header: {
			...headers
		},
        method: 'GET'
      }).then(res => {
		if(res.statusCode != 200){
			uni.$u.toast('服务器异常')
			return;
		}		  
        resolve(res.data)
        return res
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  post(url = '', data = {}, response = false) {
	url = $config.BASE_URL + url  
	headers['authentication'] = $storage.getTokenStorage()
    return new Promise((resolve, reject) => {
      uni.request({
        url,
        data: data,
        header: headers,
        method: 'POST'
      }).then(res => {
		if(res.statusCode != 200){
			uni.$u.toast('服务器异常')
			return;
		}
		const data = res.data
		if(data.code != 200 && !response){
			uni.$u.toast(data.message)
			return;
		}
        resolve(res.data)
        return res
      }).catch(error => {
        reject(error)
      })
    })
  },

  delete(url = '', data = {}) {
	url = $config.BASE_URL + url	
	headers['authentication'] = $storage.getTokenStorage()  
    return new Promise((resolve, reject) => {
      uni.request({
        url,
        data: data,
        header: headers,
        method: 'DELETE'
      }).then(res => {
		if(res.statusCode != 200){
			uni.$u.toast('服务器异常')
			return;
		}		  
        resolve(res.data)
        return res
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default http